package cn.net.Thread;
/**四个线程一起售票1~100张
 * 本类用于改造售票案例,使用可重入读写锁
 * ReentrantReadWriteLock(true)
 * */
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class SoleTicketV3 {
    public static void main(String[] args) {
        TicketV3 t= new TicketV3();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        Thread t4 = new Thread(t);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

}


class TicketV3 implements Runnable{
//出售400张票，四个线程，单次为100张
   static int tickets =100;
    //1.定义可重入读写锁对象,静态static保证全局唯一
  static   ReentrantReadWriteLock lock =  new ReentrantReadWriteLock(true);

    @Override
    public void run() {//业务在run方法里，while循环内执行
        while(true) {
            //2.在操作共享资源前;【上锁】
            lock.writeLock().lock();//!!!!!注意格式，锁对象.writeLock().lock()

            try{
                    //判断第一种
                    if(tickets>0) {
                        try {
                            Thread.sleep(10);//try/catch
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //while循环内打印有效
                        System.out.println(Thread.currentThread().getName() + "=" + tickets--);
                    }
                    //判断第二种
                     if(tickets<=0) break;
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //3.在finally{}中【释放锁】注意一定要手动释放,防止死锁,否则就独占报错了
                lock.writeLock().unlock();
            }
        }
    }
}